package audio;

import java.io.File;
import java.util.Vector;

import javax.swing.JOptionPane;

import audiobeatz.AudioBeatz;

import chords.EChord;
import chords.TimedChord;

public class ABPlayer extends Thread {

    private boolean isAskedToStop = false;
    private boolean isAskedToPause = false;

    private Vector<TimedChord> timedChords;
    private AudioBeatz callback;

    public ABPlayer(Vector<TimedChord> timedChords, AudioBeatz callback) {
	this.timedChords = timedChords;
	this.callback = callback;
    }

    @Override
    public void run() {
	while (true) {
	    for (int i = 0; i <= timedChords.size() - 1; i++) {
		callback.showReleasedChord();
		if (isAskedToStop)
		    return;

		if (isAskedToPause) {
		    try {
			Thread.sleep(20);
		    } catch (InterruptedException e) {
			e.printStackTrace();
		    }
		    break;
		}

		TimedChord currentTimedChord = timedChords.get(i);

		// Play the one we're at unless it's the Silent one
		if (currentTimedChord.getChord() != EChord.Silence)
		    new WavePlayer(currentTimedChord.getInstrument().getFolder() + File.separator + currentTimedChord.getInstrument().getFilename() + currentTimedChord.getChord().getFilename() + ".wav").start();

		// Fix the visual playback.
		callback.showPressedChord(currentTimedChord.getChord());

		// Sleep until next one.
		if (i == timedChords.size() - 1) {
		    callback.playerFinished();
		    return;
		}

		try {
		    Thread.sleep(timedChords.get(i + 1).getTime() - currentTimedChord.getTime());
		} catch (InterruptedException e) {
		    JOptionPane.showMessageDialog(null, "Playback was terminally changed by a InterruptedException.");
		    callback.playerFinished();
		    return;
		}
	    }
	}
    }

    public void askToStop() {
	isAskedToStop = true;
    }

    public void askToPause() {
	isAskedToPause = true;
    }

    public void askToResume() {
	isAskedToPause = false;
    }
}